﻿using System;
using System.Net.Mail;
using System.Net.Mime;
using System.Net;
using System.IO;
using System.Web;

namespace Zeenck.DataAccess
{
    public static class EmailModule
    {
        #region Account Confirmation

        public static void SendAccountConfirmationEmail(String firstName, String lastName, String emailAddress, String confirmationLink, Uri siteRoot)
        {
            try
            {
                String fromAddress = Configuration.Zeenck.Info.Email.Account.Welcome.FromAddress;
                String fromName = Configuration.Zeenck.Info.Email.Account.Welcome.FromName;
                String subject = Configuration.Zeenck.Info.Email.Account.Welcome.EmailSubject;
                String bodyPlainText = GeneratePlainTextAccountConfirmationEmail(firstName, lastName, confirmationLink);
                String bodyHtml = GenerateHtmlAccountConfirmationEmailTemplate(firstName, lastName, confirmationLink, siteRoot);

                SendMultiPart(emailAddress, fromAddress, fromName, subject, bodyPlainText, bodyHtml);
            }
            catch (Exception)
            {
            }
        }

        private static String GeneratePlainTextAccountConfirmationEmail(String firstName, String lastName, String confirmationLink)
        {
            String plainTextEmail;

            try
            {
                String introduction = String.Format(Configuration.Zeenck.Info.Email.Account.Welcome.EmailTemplateIntroduction, firstName, lastName);
                plainTextEmail = String.Format("{0} {1} {2} {3}", introduction, Configuration.Zeenck.Info.Email.Account.Welcome.EmailTemplateMessage, Configuration.Zeenck.Info.Email.Account.Welcome.EmailTemplateCallToAction, confirmationLink);
            }
            catch (Exception)
            {
                plainTextEmail = String.Empty;
            }

            return plainTextEmail;
        }

        private static String GenerateHtmlAccountConfirmationEmailTemplate(String firstName, String lastName, String confirmationLink, Uri siteRoot)
        {
            String template;

            try
            {
                template = LoadTemplate(Configuration.Zeenck.Info.Email.Account.Welcome.EmailTemplateFile);

                String htmlContent = String.Format("<p>{0}</p>", String.Format(Configuration.Zeenck.Info.Email.Account.Welcome.EmailTemplateIntroduction, firstName, lastName));
                htmlContent += String.Format("<p>{0}</p>", Configuration.Zeenck.Info.Email.Account.Welcome.EmailTemplateMessage);
                htmlContent += String.Format("<p>{0}</p>", Configuration.Zeenck.Info.Email.Account.Welcome.EmailTemplateCallToAction);
                htmlContent += String.Format("<p><a href=\"{0}\">{1}</a></p>", confirmationLink, confirmationLink);

                template = template.Replace("*|LOGO|*", new UriBuilder(siteRoot.Scheme, siteRoot.Host, siteRoot.Port, Configuration.Zeenck.Info.Email.Account.Welcome.EmailTemplateLogo).ToString());
                template = template.Replace("*|SUBJECT|*", Configuration.Zeenck.Info.Email.Account.Welcome.EmailSubject);
                template = template.Replace("*|TEASER|*", GeneratePlainTextAccountConfirmationEmail(firstName, lastName, confirmationLink));
                template = template.Replace("*|CONTENT|*", htmlContent);
            }
            catch (Exception)
            {
                template = String.Empty;
            }

            return template;
        }

        #endregion Account Confirmation

        #region Password Reset

        public static void SendAccountPasswordResetEmail(String firstName, String lastName, String emailAddress, String confirmationLink, Uri siteRoot)
        {
            try
            {
                String fromAddress = Configuration.Zeenck.Info.Email.Account.ResetPassword.FromAddress;
                String fromName = Configuration.Zeenck.Info.Email.Account.ResetPassword.FromName;
                String subject = Configuration.Zeenck.Info.Email.Account.ResetPassword.EmailSubject;
                String bodyPlainText = GeneratePlainTextAccountPasswordResetEmail(firstName, lastName, confirmationLink);
                String bodyHtml = GenerateHtmlAccountPasswordResetEmailTemplate(firstName, lastName, confirmationLink, siteRoot);
                SendMultiPart(emailAddress, fromAddress, fromName, subject, bodyPlainText, bodyHtml);
            }
            catch (Exception)
            {
            }
        }

        private static String GeneratePlainTextAccountPasswordResetEmail(String firstName, String lastName, String confirmationLink)
        {
            String plainTextEmail;

            try
            {
                String introduction =
                    String.Format(Configuration.Zeenck.Info.Email.Account.ResetPassword.EmailTemplateIntroduction,
                                  firstName, lastName);
                plainTextEmail = String.Format("{0} {1} {2} {3}", introduction,
                                               Configuration.Zeenck.Info.Email.Account.ResetPassword.
                                                   EmailTemplateMessage,
                                               Configuration.Zeenck.Info.Email.Account.ResetPassword.
                                                   EmailTemplateCallToAction, confirmationLink);
            } catch(Exception)
            {
                plainTextEmail = String.Empty;
            }

            return plainTextEmail;
        }

        private static String GenerateHtmlAccountPasswordResetEmailTemplate(String firstName, String lastName, String confirmationLink, Uri siteRoot)
        {
            String template;

            try
            {
                template = LoadTemplate(Configuration.Zeenck.Info.Email.Account.ResetPassword.EmailTemplateFile);

                String htmlContent = String.Format("<p>{0}</p>", String.Format(Configuration.Zeenck.Info.Email.Account.ResetPassword.EmailTemplateIntroduction, firstName, lastName));
                htmlContent += String.Format("<p>{0}</p>", Configuration.Zeenck.Info.Email.Account.ResetPassword.EmailTemplateMessage);
                htmlContent += String.Format("<p>{0}</p>", Configuration.Zeenck.Info.Email.Account.ResetPassword.EmailTemplateCallToAction);
                htmlContent += String.Format("<p><a href=\"{0}\">{1}</a></p>", confirmationLink, confirmationLink);

                template = template.Replace("*|LOGO|*", new UriBuilder(siteRoot.Scheme, siteRoot.Host, siteRoot.Port, Configuration.Zeenck.Info.Email.Account.ResetPassword.EmailTemplateLogo).ToString());
                template = template.Replace("*|SUBJECT|*", Configuration.Zeenck.Info.Email.Account.ResetPassword.EmailSubject);
                template = template.Replace("*|TEASER|*", GeneratePlainTextAccountPasswordResetEmail(firstName, lastName, confirmationLink));
                template = template.Replace("*|CONTENT|*", htmlContent);
                template = template.Replace("*|CUSTOMERSUPPORTEMAIL|*", Configuration.Zeenck.CustomerSupport.Email);
                template = template.Replace("*|COPYRIGHT|*", HttpUtility.HtmlEncode(Configuration.Zeenck.Info.Footer.CopyRightText));
            }
            catch (Exception)
            {
                template = String.Empty;
            }

            return template;
        }

        #endregion Password Reset

        #region General

        private static void SendMultiPart(String toAddress, String fromAddress, String fromName, String subject, String bodyPlainText, String bodyHtml)
        {
            try
            {
                var client = new SmtpClient(Configuration.Zeenck.Info.Email.ExchangeServerHost,
                                            Configuration.Zeenck.Info.Email.ExchangeServerPort)
                                 {
                                     DeliveryMethod = SmtpDeliveryMethod.Network,
                                     Credentials = new NetworkCredential("noreply@zeenck.com", "zeenck2011")
                                 };

                var plainText = AlternateView.CreateAlternateViewFromString(bodyPlainText, new ContentType("text/plain"));
                var html = AlternateView.CreateAlternateViewFromString(bodyHtml, new ContentType("text/html"));

                var message = new MailMessage {From = new MailAddress(fromAddress, fromName)};
                message.To.Add(new MailAddress(toAddress));
                message.Subject = subject;
                message.AlternateViews.Add(plainText);
                message.AlternateViews.Add(html);
                message.IsBodyHtml = true;

                client.Send(message);
            }
            catch (Exception)
            {
            }
        }

        private static String LoadTemplate(String relativePath)
        {
            String text;

            try
            {
                String filePath = AppDomain.CurrentDomain.BaseDirectory;
                filePath = Path.Combine(filePath, relativePath);

                using (var streamReader = new StreamReader(filePath))
                {
                    text = streamReader.ReadToEnd();
                }
            }
            catch (Exception)
            {
                text = String.Empty;
            }

            return text;
        }

        #endregion General
    }
}